package cn.sypt.yuhao.dao;

import java.sql.SQLException;
import java.util.concurrent.TimeoutException;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import cn.itcast.jdbc.TxQueryRunner;
import cn.sypt.yuhao.domain.User;

public class UserDao {
	private QueryRunner qr = new TxQueryRunner();
	public User ajaxUser(String uname) {
		String sql="select * from user where uname=?";
		try {
			User user=qr.query(sql, new BeanHandler<User>(User.class),uname);
			return user;
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
	public User ajaxEmail(String email) {
		String sql="select * from user where uemail=?";
		try {
			User user=qr.query(sql, new BeanHandler<User>(User.class),email);
			return user;
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
	public void regist(User user) {
		//System.out.println(user);
		user.setUimage("co.png");
		user.setLevel(0);
		String sql = "insert into user values(?,?,?,?,?,?,?,?,?,?,?)";
		Object[] params = { user.getUid(), user.getUname(), user.getUpass(),
				user.getUemail(), user.getUaddress(), user.getUbirth(),
				user.getUphone(), user.getUimage(), user.getActive(),
				user.getLevel(),user.getUtime() };
		try {
			qr.update(sql, params);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public User login(String uname, String upass) {
		String sql = "select * from user where uname=? and upass=?";
		try {
			User user = qr.query(sql, new BeanHandler<User>(User.class), uname,
					upass);
			return user;
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}

	}

	public Object findByActive(String active) {
		String sql = "select level from user where active=?";
		try {
			Object level = qr.query(sql, new ScalarHandler(), active);
			if (level == null) {
				level = 500;
			}
			return level;
		} catch (SQLException e) {
			// return null;
			throw new RuntimeException(e);
		}

	}

	public int findBylevel(String uname,String upass) {
	String sql="select level from user where uname=? and upass=?";
	try {
		int level=  (Integer) qr.query(sql, new ScalarHandler(),uname,upass);
		System.out.println(level);
		return level;
	} catch (SQLException e) {
		throw new RuntimeException(e);
	}
	}

	public void active(String active) {
		String sql = "update user set level=1 where active=?";
		try {
			qr.update(sql, active);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

}
